const express = require('express')
// 引入路由
const router = express.Router();
//引入封装好的数据库操作
let db = require('../db.js');
const util = require("../utils/index")

//TODO 分页 tag查询 评论相关逻辑

//page
router.get('/getArticleNum', (req, res) => {
    let sql = db.getArticleNum()
    db.Query(sql).then(data => {
        res.send({
            code: 200,
            message: "查询成功",
            data: {
                num: data[0].number
            }
        })
    }).catch(err =>
        res.send({ "code": 400, "message": "服务器开小差了", data: {} })
    )
})

//获取文章列表的接口
router.get('/getArticles', (req, res) => {
    if (!req.query.page || !req.query.pageSize) {
        res.send({ "code": 400, "message": "服务器开小差了", data: {} });
        return
    }
    let page = req.query.page
    let pageSize = req.query.pageSize

    let sql = db.getArticleListByPage(page, pageSize)

    db.Query(sql).then(data => {
        res.send({ "code": 200, message: "查询成功", data });
    }, err => {
        res.send({ "code": 400, "message": "服务器开小差了", data: {} });
    })
});

//根据id获取单篇文章的接口
router.get('/oneArticle', (req, res) => {
    console.log("enetr")
    if (!req.query.id) {
        res.send({ "code": 400, "message": "服务器开小差了", data: {} });
        return
    }
    let id = req.query.id;
    let sql = db.getArticleDetail(id);
    console.log('获取单篇文章');
    db.Query(sql).then(data => {
        if (data.length !== 1) {
            return Promise.reject("无相关文章")
        }
        res.send({ "code": 200, message: "查询成功", "data": data[0] });
    }).catch(err => {
        res.send({ "code": 400, "message": err || "服务器开小差了" });
    })
});

// //根据标签获取文章接口
// router.get('/tagPassages', (req, res) => {
//     let tag = req.query.tag;
//     let sql = db.tagPassagesFront(tag);
//     console.log('前端根据标签获取文章列表');
//     db.Query(sql).then(data => {
//         console.log(data);
//         res.send({ "code": "200", "data": data });
//     }, err => {
//         res.send({ "code": "服务器开小差了！" });
//     })
// })

// // 根据关键字获取相应文章接口（大坑，先做一个最基础最简单的）
// router.get('/searchPassages', (req, res) => {
//     let str = req.query.str;
//     let sql = db.searchPassageFront(str);
//     console.log('前端根据关键字获取文章列表');
//     db.Query(sql).then(data => {
//         console.log(data);
//         res.send({ "code": "200", "data": data });
//     }, err => {
//         res.send({ "code": "服务器开小差了！" });
//     })
// })

//发表评论
router.post('/addComment', (req, res) => {
    let comment = req.body;
    let uid = req.auth.id
    comment["uid"] = uid
    async function func() {
        try{
            let sql = db.addComment(comment);
            let data=await db.Query(sql)
            let insertId=data.insertId
            sql=db.getCommentByCommentId(insertId)
            data=await db.Query(sql)
            let responseData={...data[0],children:[]}
            res.send({ "code": 200, "message": "添加成功", data: responseData });
        }catch(e){
            res.send({ "code": 400, "message": "服务器错误，添加失败", data: {} });
        }
    }
    func()

})

//获取评论
router.get('/getComments', (req, res) => {
    console.log(req.query);
    let id = req.query.id;
    let sql = db.getCommentsById(id);

    db.Query(sql).then(data => {
        let treelist = util.tranListToTreeData(data)
        res.send({ "code": 200, "message": "获取成功", data: treelist });
    }, err => {
        console.log(err)
        res.send({ "code": 400, "message": "获取失败", data: {} });
    })
})

//文章存储接口（包括了新建文章和修改文章）
router.post('/saveArticle', (req, res) => {
    console.log(req.auth.name)
    if (req.auth.name !== "admin") {
        res.send({
            code: 402,
            message: "无权限访问"
        })
        return
    }

    let article = req.body;
    let id = parseInt(article.id);
    // 如果id存在，那么执行更新操作
    if (id !== 0) {
        console.log('id存在，执行更新操作！')
        let sql = db.updateArticle(article);
        db.Query(sql,article.content).then(data => {
            res.send({ "code": 200, "message": "更新成功", data: {} });
        }, err => {
            res.send({ "code": 400, "message": "更新失败", data: {} });
            console.log(err);
        })
    }
    // 如果req.body的id不存在，说明是一篇新的文章,执行插入操作;
    else {
        console.log('id不存在，执行插入操作！')
        let sql = db.addNewArticle(article);
        db.Query(sql,article.content).then(data => {
            res.send({ "code": 200, "message": "新增成功", data });
            //res.send({"code":"200","data":data});
        }, err => {
            res.send({ "code": 400, "message": "新增失败", data: {} });
            console.log(err);
        })
    }
})

//文章删除接口
router.post('/deleteArticle', (req, res) => {
    console.log(req.auth.name)
    if (req.auth.name !== "admin") {
        res.send({
            code: 402,
            message: "无权限访问"
        })
        return
    }
    let id = req.body.id;
    let sql = db.deleteAritle(id);
    db.Query(sql).then(data => {
        res.send({ "code": 200, "message": "删除成功", data: {} });
    }, err => {
        res.send({ "code": 400, "message": "删除失败", data: err });
        console.log(err);
    })
})

// 将路由对象共享出去
module.exports = router